﻿using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using SDCloudSolution.SDCloud.DataLayer.Interfaces;
using SDCloudSolution.SDCloud.Entities.Identity.OAuth;

namespace SDCloudSolution.SDCloud.DataLayer.Identity
{
    /// <summary>
    /// Implements methods for works client applications via Entity Framework.
    /// </summary>
    public class ClientApplicationDataProvider : IClientApplicationDataProvider
    {
        private readonly ClientApplicationDbContext _clientApplicationDbContext;

        protected IDbSet<ClientApplicationEntity> ClientApplications
        {
            get { return _clientApplicationDbContext.ClientApplications; }
        }

        public ClientApplicationDataProvider(ClientApplicationDbContext clientApplicationDbContext)
        {
            _clientApplicationDbContext = clientApplicationDbContext;
        }

        /// <summary>
        /// Finds a <see cref="ClientApplicationEntity"/> by specific specific application identifier.
        /// </summary>
        /// <param name="applicationId">The application identifier.</param>
        public ClientApplicationEntity GetById(int applicationId)
        {
            return ClientApplications.First(application => application.Id == applicationId);
        }

        /// <summary>
        /// Finds a <see cref="ClientApplicationEntity"/> by specific client identifier.
        /// </summary>
        /// <param name="clientId">The client identifier.</param>
        public ClientApplicationEntity GetByClientId(string clientId)
        {
            return ClientApplications
                .FirstOrDefault(application => application.ClientId == clientId);
        }

        /// <summary>
        /// Finds <see cref="ClientApplicationEntity"/>'s that attached to specific user.
        /// </summary>
        /// <param name="userId">The user identifier.</param>
        /// <returns></returns>
        public IList<ClientApplicationEntity> GetByUserId(int userId)
        {
            return ClientApplications
                .Where(application => application.UserId == userId)
                .ToList();
        }

        /// <summary>
        /// Inserts the new <see cref="ClientApplicationEntity"/> into storage.
        /// </summary>
        /// <param name="application">The application.</param>
        /// <returns></returns>
        public ClientApplicationEntity Insert(ClientApplicationEntity application)
        {
            var result = ClientApplications.Add(application);
            _clientApplicationDbContext.SaveChanges();
            return result;
        }
    }
}
